import { EditOutlined, LogoutOutlined, PictureOutlined, UserOutlined } from '@ant-design/icons';
import { Form, Input, Modal, Tooltip, Upload } from 'antd';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

import { logoutProxy, userProxy } from '@/store/userStore';
import messageBox from '@/utils/messageBox';

import { changePassword } from '../service';

const UserActions = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [modal, contextHolder] = Modal.useModal();

  // 修改密码
  const clickChangePassword = () => {
    modal.confirm({
      icon: null,
      centered: true,
      content: (
        <Form form={form} labelCol={{ span: 10 }} colon={false} labelAlign="left">
          <Form.Item name="oldPassword" label={t('passwordChangeOld')}>
            <Input />
          </Form.Item>
          <Form.Item name="newPassword" label={t('passwordChangeNew')}>
            <Input.Password />
          </Form.Item>
          <Form.Item name="confirmPassword" label={t('passwordChangeConfirm')}>
            <Input.Password />
          </Form.Item>
        </Form>
      ),
      maskClosable: true,
      okType: 'default',
      async onOk(close) {
        await changePassword(form.getFieldsValue()).then(res => {
          messageBox.success({ content: res.data.msg });
          form.resetFields();
          close();
        });
      },
    });
  };

  const handlerChange = (v: any) => {
    // 上传成功后后的回调
    if (v?.file?.response && v.file.percent === 100) {
      const { response } = v.file;
      if (response.url.indexOf('avatar') !== -1) {
        userProxy.avatar = response.url;
      } else {
        userProxy.background = response.url;
      }
      messageBox.success({ content: 'Avatar uploaded successfully' });
    }
  };

  // 登出
  const logout = () => {
    logoutProxy();
    navigate('/');
  };

  return [
    <Tooltip title={t('passwordChange')}>
      <EditOutlined onClick={clickChangePassword} />
      {contextHolder}
    </Tooltip>,
    <Tooltip title={t('uploadAvatar')}>
      <Upload
        headers={{ Authorization: `Bearer ${userProxy.token}` }}
        showUploadList={false}
        action="/avatar"
        onChange={handlerChange}
      >
        <UserOutlined />
      </Upload>
    </Tooltip>,
    <Tooltip title={t('uploadBackground')}>
      <Upload
        headers={{ Authorization: `Bearer ${userProxy.token}` }}
        showUploadList={false}
        action="/background"
        onChange={handlerChange}
      >
        <PictureOutlined />
      </Upload>
    </Tooltip>,
    <Tooltip title={t('logout')}>
      <LogoutOutlined onClick={logout} />
    </Tooltip>,
  ];
};

export default UserActions;
